package com.dh.project.controller;

import com.alibaba.fastjson.JSON;
import com.dh.project.model.*;
import com.dh.project.model.push.AudienceBean;
import com.dh.project.model.push.PageType;
import com.dh.project.other.ModelRes;
import com.dh.project.service.*;
import com.dh.project.utils.PushUtil;
import com.dh.project.utils.StringUtil;
import com.dh.project.utils.WorkerPushUtil;
import com.dh.project.view.OrderInfoView;
import com.dh.project.view.OrderListView;
import com.dh.project.view.ResultNewOrderId;
import com.dh.project.websoket.SendUtil;
import com.dh.project.websoket.WebSocketMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by admin on 2017/4/24.
 */
@Controller
public class OrderController {

    private OrderInfoService orderInfoService;

    private CustomerAddressService customerAddressService;

    private EmployeeInfoService employeeInfoService;

    private OrderServiceProjectService orderServiceProjectService;

    private CustomerInfoService customerInfoService;

    private SuggestService suggestService;

    private CustomerCouponService customerCouponService;

    private CouponService couponService;

    private IndoorpriceService indoorpriceService;

    @Autowired
    private OrderController(OrderInfoService orderInfoService, CustomerAddressService customerAddressService,
                            EmployeeInfoService employeeInfoService, OrderServiceProjectService orderServiceProjectService,
                            CustomerInfoService customerInfoService, SuggestService suggestService,
                            CustomerCouponService customerCouponService, CouponService couponService,
                            IndoorpriceService indoorpriceService) {
        this.orderInfoService = orderInfoService;
        this.customerAddressService = customerAddressService;
        this.employeeInfoService = employeeInfoService;
        this.orderServiceProjectService = orderServiceProjectService;
        this.customerInfoService = customerInfoService;
        this.suggestService = suggestService;
        this.customerCouponService = customerCouponService;
        this.couponService = couponService;
        this.indoorpriceService = indoorpriceService;
    }


    /**
     * 查询客户订单列表
     *
     * @param customer_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectCustomerOrderList", produces = "text/html;charset=utf-8")
    public Object selectCustomerOrderList(int customer_id, int type) {
        Map map = new HashMap();
        map.put("customer_id", customer_id);
        List<OrderListView> orderListViews = new ArrayList<OrderListView>();
        if (type == 1) {//进行中订单
            orderListViews = orderInfoService.selectOrderDoingListByMap(map);
            if (orderListViews == null || orderListViews.size() < 1) {
                return new ModelRes(ModelRes.Status.ERROR, "未查到进行中订单！");
            }
        } else if (type == 2) {// 已完成订单
            orderListViews = orderInfoService.selectOrderOverListByMap(map);
            if (orderListViews == null || orderListViews.size() < 1) {
                return new ModelRes(ModelRes.Status.ERROR, "未查到已完成订单！");
            }
        }
        return new ModelRes(orderListViews);
    }

    /**
     * 查询订单详情
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectOrderInfoById", produces = "text/html;charset=utf-8")
    public Object selectCustomerOrder(int order_id) {
        Map map = new HashMap();
        map.put("order_id", order_id);
        OrderInfoView orderInfoView = orderInfoService.selectOrderInfoViewByMap(map);
        List<OrderServiceProject> orderServiceProjects = orderServiceProjectService.selectByMap(map);
        if (orderServiceProjects == null) {
            orderServiceProjects = new ArrayList<OrderServiceProject>();
        }
        if (orderInfoView == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查到该订单！");
        }
        orderInfoView.setOrderServiceProjects(orderServiceProjects);
        return new ModelRes(orderInfoView);
    }

    //查询上门服务费接口
    @ResponseBody
    @RequestMapping(value = "getIndoorPrice", produces = "text/html;charset=utf-8")
    public Object getIndoorPrice() {
        Indoor_price indoorPrice = indoorpriceService.selectById(1);
        if (indoorPrice == null) {
            return new ModelRes(ModelRes.Status.ERROR, "服务费未设定！");

        } else {
            Map map = new HashMap();
            map.put("indoor_price", indoorPrice.getIndoor_price());
            return new ModelRes(map);
        }
    }

    /**
     * 添加订单
     *
     * @param orderInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "insertCustomerOrder", produces = "text/html;charset=utf-8")
    public Object insertCustomerOrder(OrderInfo orderInfo) {
        /* double a = 0;*/
        CustomerInfo customerInfo = customerInfoService.selectById(orderInfo.getCustomer_id());
        Indoor_price indoorPrice = indoorpriceService.getIndoorPrice(1);
        if (customerInfo == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查到该用户信息!");
        } else if (indoorPrice == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查到服务费!");
        }
        if (customerInfo.getIs_freeze() == 2) {
            return new ModelRes(ModelRes.Status.ERROR, "您的账号已被冻结，不能进行下单操作！");
        }
        orderInfo.setEmployee_id(0);
        orderInfo.setOrder_status(1);
        orderInfo.setOver_time(orderInfo.getReserve_date());
        orderInfo.setOrder_remark("无");
        orderInfo.setOrder_grade(5);
        orderInfo.setCustomer_coupon_id(0);
        if (orderInfo.getIsInsurance() == 1) {
            orderInfo.setOrder_price(0.00);
            orderInfo.setIndoor_price(0);
        } else {
            orderInfo.setOrder_price(indoorPrice.getIndoor_price());
            orderInfo.setIndoor_price(indoorPrice.getIndoor_price());
        }
        orderInfo.setCoupon_price(0.00);
        orderInfo.setCreatetime(String.valueOf(System.currentTimeMillis()));
        orderInfo.setModifytime(String.valueOf(System.currentTimeMillis()));
        boolean isSuccess = orderInfoService.insert(orderInfo);
        if (isSuccess) {
            //订单添加成功  向后台发送消息
            Suggest suggest = new Suggest();
            suggest.setCreatetime(String.valueOf(System.currentTimeMillis()));
            suggest.setCustomer_id(orderInfo.getCustomer_id());
            suggest.setIs_do(1);
            suggest.setSuggest_content("您有一笔新订单,客户id为" + orderInfo.getCustomer_id());
            suggest.setOrder_id(orderInfo.getOrder_id());
            suggestService.insert(suggest);
            SendUtil.sendMessage(new WebSocketMsg("您有一笔新订单,客户id为" + orderInfo.getCustomer_id(), 0 + ""));
            //推送
            List<String> aliasList = new ArrayList<>();
            aliasList.add(customerInfo.getCustomer_id().toString());
            PushUtil.pushOne(aliasList, "正在为你匹配专业师傅，请稍候!", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
            return new ModelRes(new ResultNewOrderId(orderInfo.getOrder_id()));
        } else {
            return new ModelRes(ModelRes.Status.ERROR, "添加失败");
        }
    }

//    /**
//     * 修改订单状态
//     * @param order_id
//     * @param order_status
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "updateOrderStatus",produces = "text/html;charset=utf-8")
//    public Object updateOrderStatus(int order_id,int order_status) {
//        OrderInfo orderInfo = orderInfoService.selectById(Long.valueOf(order_id));
//        orderInfo.setOrder_status(order_status);
//        boolean isSuccess = orderInfoService.updateById(orderInfo);
//        if (isSuccess){
//            return new ModelRes(ModelRes.Status.SUCCESS,"修改成功",orderInfo);
//        }else {
//            return new ModelRes(ModelRes.Status.ERROR,"修改失败");
//        }
//    }

    /**
     * 客户确认上门
     *
     * @param order_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "customerVisitTrue", produces = "text/html;charset=utf-8")
    public Object customerVisitTrue(int order_id) {
        OrderInfo orderInfo = orderInfoService.selectById(order_id);
        if (orderInfo == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查询到订单信息!");
        }
        if (orderInfo.getOrder_status() != 2) {
            return new ModelRes(ModelRes.Status.ERROR, "订单状态错误，无法确认上门！");
        }
        orderInfo.setOrder_status(3);
        boolean isSuccess = orderInfoService.updateById(orderInfo);
        if (isSuccess) {
            //订单状态改变时推送
            List<String> aliasList = new ArrayList<>();
            aliasList.add(orderInfo.getCustomer_id().toString());
            PushUtil.pushOne(aliasList, "师傅已到达您的报修地址，向师傅详细描述下您的设备问题吧。", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
            aliasList.clear();
            aliasList.add(orderInfo.getEmployee_id().toString());
            WorkerPushUtil.pushOne(aliasList, "订单" + orderInfo.getOrder_id() + "；客户已确认您到达目的地。请查看订单并开始检修！", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
            return new ModelRes();
        } else {
            return new ModelRes(ModelRes.Status.ERROR, "数据更改失败！");
        }
    }

//    /**
//     * 客户确认上门
//     * @param order_id
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "customerVisitTrue",produces = "text/html;charset=utf-8")
//    public Object customerVisitTrue(int order_id){
//        OrderInfo orderInfo = orderInfoService.selectById(order_id);
//        if (orderInfo.getOrder_status() != 2){
//            return new ModelRes(ModelRes.Status.ERROR,"订单状态错误，无法确认上门！");
//        }
//        orderInfo.setOrder_status(3);
//        boolean isSuccess = orderInfoService.updateById(orderInfo);
//        if (isSuccess){
//            return new ModelRes();
//        }else {
//            return new ModelRes(ModelRes.Status.ERROR,"数据更改失败！");
//        }
//    }

    /**
     * 添加评价
     *
     * @param order_id
     * @param order_grade
     * @param order_remark
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "customerAddEvaluate", produces = "text/html;charset=utf-8")
    public Object customerAddEvaluate(int order_id, int order_grade, String order_remark) {
        OrderInfo orderInfo = orderInfoService.selectById(order_id);
        if (orderInfo == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查询到订单信息!");
        }
        if (orderInfo.getOrder_status() != 7) {
            return new ModelRes(ModelRes.Status.ERROR, "订单未完成不能评价！");
        }
        orderInfo.setOrder_grade(order_grade);
        orderInfo.setOrder_remark(order_remark);
        boolean isSuccess = orderInfoService.updateById(orderInfo);
        if (!isSuccess) {
            return new ModelRes(ModelRes.Status.ERROR, "评价订单失败！");
        }
        Map map = new HashMap();
        map.put("employee_id", orderInfo.getEmployee_id());
        map.put("order_status", 7);
        //计算工人平均评分
        List<OrderInfo> orderInfos = orderInfoService.selectByMap(map);
        double all_grade = 0.0;
        for (int i = 0; i < orderInfos.size(); i++) {
            all_grade = all_grade + orderInfos.get(i).getOrder_grade();
        }
        int grade = (int) (all_grade / orderInfos.size());
        EmployeeInfo employeeInfo = employeeInfoService.selectById(orderInfo.getEmployee_id());
        employeeInfo.setGrade_number(grade);
        employeeInfoService.updateById(employeeInfo);
        return new ModelRes();
    }

    /**
     * 客户确认服务项
     *
     * @param order_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "customerAffirmService", produces = "text/html;charset=utf-8")
    public Object customerAffirmService(int order_id) {
        OrderInfo orderInfo = orderInfoService.selectById(order_id);
        if (orderInfo == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查询到订单信息!");
        }
        if (orderInfo.getOrder_status() != 4) {
            return new ModelRes(ModelRes.Status.ERROR, "该订单状态下不能确认服务项目！");
        }
        orderInfo.setOrder_status(5);
        orderInfo.setModifytime(String.valueOf(System.currentTimeMillis()));
        orderInfoService.updateById(orderInfo);
        List<String> aliasList = new ArrayList<>();
        aliasList.add(orderInfo.getCustomer_id().toString());
        PushUtil.pushOne(aliasList, "当师傅维修完成后，请您注意开机验收后付款!", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
        aliasList.clear();
        aliasList.add(orderInfo.getEmployee_id().toString());
        WorkerPushUtil.pushOne(aliasList, "订单" + orderInfo.getOrder_id() + "；用户已同意并确认了您提交的维修内容，请开始维修", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
        return new ModelRes();
    }

    /**
     * 客户支付
     *
     * @param order_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "customerPay", produces = "text/html;charset=utf-8")
    public Object customerPay(int order_id, int coupon_id,double price) {
        OrderInfo orderInfo = orderInfoService.selectById(order_id);
        if (orderInfo == null) {
            return new ModelRes(ModelRes.Status.ERROR, "未查询到订单信息!");
        }
        CustomerCoupon customerCoupon = null;
        if (coupon_id != 0) {
            customerCoupon = customerCouponService.selectById(coupon_id);

            if (customerCoupon.getIs_use() == 2) {
                return new ModelRes(ModelRes.Status.ERROR, "该优惠券已过期！");
            }
            if (customerCoupon.getIs_out() == 2) {
                return new ModelRes(ModelRes.Status.ERROR, "该优惠券已使用！");
            }
        }
        if (orderInfo.getOrder_status() != 5) {
            return new ModelRes(ModelRes.Status.ERROR, "该订单状态下不能支付！");
        }
        if (coupon_id != 0) {
            Coupon coupon = couponService.selectById(customerCoupon.getCoupon_id());
            if (coupon == null) {
                return new ModelRes(ModelRes.Status.ERROR, "未查询到优惠券信息!");
            }
            orderInfo.setCoupon_price(coupon.getPrice().doubleValue());
            orderInfo.setCustomer_coupon_id(coupon_id);
            double orderPrice = StringUtil.doubleSub(orderInfo.getOrder_price(), orderInfo.getCoupon_price());
            orderPrice = orderPrice < 0 ? 0 : orderPrice;
//            if(orderPrice!=price){
//                return new ModelRes(ModelRes.Status.ERROR, "价格错误!");
//            }
            orderInfo.setOrder_price(price);
            customerCoupon.setIs_out(2);
            if (!customerCouponService.updateById(customerCoupon)) {
                return new ModelRes(ModelRes.Status.ERROR, "优惠券使用错误!");
            }
        }


        //回调后操作
        orderInfo.setOrder_status(6);
        orderInfo.setModifytime(String.valueOf(System.currentTimeMillis()));
        if (!orderInfoService.updateById(orderInfo)) {
            return new ModelRes(ModelRes.Status.ERROR, "订单更新失败!");
        }

        List<String> aliasList = new ArrayList<>();
        aliasList.add(orderInfo.getCustomer_id().toString());
        PushUtil.pushOne(aliasList, "现金支付请求成功，请付款后等待师傅确认!", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
        aliasList.clear();
        aliasList.add(orderInfo.getEmployee_id().toString());
        WorkerPushUtil.pushOne(aliasList, "订单" + orderInfo.getOrder_id() + "；用户提交了现金支付申请，请尽快确认！", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));

        return new ModelRes(ModelRes.Status.SUCCESS, "现金支付申请已提交！");
    }

}
